package com.it.park.controller.expose;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.it.park.client.service.ArticleCollectService;
import com.it.park.client.service.ArticleCommentService;
import com.it.park.client.service.ArticleService;
import com.it.park.client.service.ArticleTypeService;
import com.it.park.client.service.SensitiveWordService;
import com.it.park.client.service.UserFriendService;
import com.it.park.common.JsonObj;
import com.it.park.common.Page;
import com.it.park.constant.Constant;
import com.it.park.model.Article;
import com.it.park.model.ArticleCollect;
import com.it.park.model.ArticleComment;
import com.it.park.model.ArticleType;
import com.it.park.model.SensitiveWord;
import com.it.park.model.UserFriend;
import com.it.park.rms.client.model.User;
import com.it.park.rms.client.service.UserService;

@Controller
@RequestMapping("/expose/article")
public class ExposeArticleController {
	private String rootPath=Constant.EXPOSE_PATH;

	@Autowired
	private ArticleService articleService;
	@Autowired
	private ArticleTypeService articleTypeService;
	@Autowired
	private ArticleCommentService articleCommentService;
	@Autowired
	private ArticleCollectService articleCollectService;
	@Autowired
	private UserService userService;
	@Autowired
	private SensitiveWordService sensitiveWordService;
	@Autowired
	private UserFriendService userFriendService;
	private Page page = null;
	
	@RequestMapping("list")
	public String list(@RequestParam("pageNow") Integer pageNow,HttpServletRequest request){
			List<Article> articles =	null;
			Map<String,Object> map = new HashMap<String, Object>();
			Integer totals = articleService.selectTotal(map);
			page = new Page(pageNow,totals,10);
			map.put("startPos", page.getStartPos());
			map.put("pageSize", page.getPageSize());
			articles = articleService.listRelationUser(map);
			request.setAttribute("totals", totals);
			request.setAttribute("page", page);
			request.setAttribute("articles", articles);
			
			return rootPath+"article/articleList";
	}
	
	/**
	 *单个文章详情 
	 */
	@RequestMapping("detail/{id}")
	public String detail(@PathVariable("id")Integer id,HttpServletRequest request,HttpSession session){
		String pageNow = request.getParameter("pageNow");
		if(id != null){
			articleService.updateClickRate(id);//每点击一次，加1
			Article article = articleService.selectByPrimaryKey(id);
			User user = (User) session.getAttribute("user");
			article.setUser(user);
			request.setAttribute("article", article);
			//你可能还感兴趣的文章，简单写法
			List<Article> articles =	articleService.selectOtherInterested(id);
			request.setAttribute("articles", articles);
			//发表该文章的作者
			User u = userService.selectByPrimaryKey(article.getUserId());
			request.setAttribute("u", u);
		}
		Map< String, Object> map = new HashMap<String, Object>();
		map.put("articleId", id);
		Integer total =  articleCommentService.selectTotal(map);
		if(pageNow != null){
			page = new Page(Integer.parseInt(pageNow),total,10);
		}else{
			page = new Page(1,total,10);
		}
		map.put("startPos", page.getStartPos());
		map.put("pageSize", page.getPageSize());
		List<ArticleComment> comments =	articleCommentService.selectPagination(map);
		request.setAttribute("total", total);
		request.setAttribute("page", page);
		request.setAttribute("comments", comments);
		
		return rootPath+"article/articleDetail";
	}
	
	/**
	 * 评论显示图片
	 */
	@RequestMapping("showPicture/{id}")
	public void showPicture(@PathVariable("id")Integer id,HttpServletResponse response) throws IOException{
		User user =	userService.selectByPrimaryKey(id);
		byte[] data = user.getPicture();
		response.setContentType("image/jpg");
		response.setCharacterEncoding("utf-8");
		OutputStream os = response.getOutputStream();
		InputStream is = new ByteArrayInputStream(data);
		int len = 0;
		byte[] b = new byte[1024];
		while((len = is.read(b)) != -1){
			os.write(b, 0, len);
		}
		os.close();
		is.close();
}
	
	/**
	 *文章支持、吐槽、收藏
	 */
	@RequestMapping("view")
	@ResponseBody
	public JsonObj view(Integer id, Integer type,HttpServletRequest request,HttpSession session){
		Map< String, Object> map = new HashMap<String, Object>();
		JsonObj json = new JsonObj();
		map.put("id", id);
		User user = (User) session.getAttribute("user");
		Article article = null;
		boolean success;
		if(user != null){
			map.put("type", type);
			switch (type) {
			case 1://支持
				article =articleService.selectByPrimaryKey(id);
				article.setSupportNum(article.getSupportNum()+1);
				success = articleService.updateByPrimaryKeySelective(article);
				if(success){
					json.setSuccess(Constant.S);
					json.setMessage(Constant.SUECSS_MSG_ZHICHI);
					json.setObject(article);
				}else{
					json.setSuccess(Constant.F);
					json.setMessage(Constant.FAIL_MSG_ZHICHI);
				}
				break;
			case 2://吐槽
				article =articleService.selectByPrimaryKey(id);
				article.setOpposeNum(article.getOpposeNum()+1);
				success = articleService.updateByPrimaryKeySelective(article);
				if(success){
					json.setSuccess(Constant.S);
					json.setMessage(Constant.SUECSS_MSG_TUCAO);
					json.setObject(article);
				}else{
					json.setSuccess(Constant.F);
					json.setMessage(Constant.FAIL_MSG_TUCAO);
				}
				break;

			default://收藏
				ArticleCollect collect = new ArticleCollect();
				collect.setUserId(user.getId());
				collect.setArticleId(id);
				ArticleCollect collect_ = articleCollectService.selectIsExists(collect);
				if(collect_ == null){//没收藏过、收藏过提示不再收藏	
					article =articleService.selectByPrimaryKey(id);
					article.setCollectNum(article.getCollectNum()+1);
					articleService.updateByPrimaryKeySelective(article);
					articleCollectService.insert(collect);
					json.setSuccess(Constant.S);
					json.setMessage(Constant.SUCCESS_COLLECTION);
					json.setObject(article);
				}else{
					json.setSuccess(Constant.F);
					json.setMessage(Constant.FAIL_COLLECTION);
				}
				break;
			}
		}else{
			json.setSuccess(Constant.F);
			json.setCode(Constant.NOT_LOGGED102);
			json.setMessage(Constant.NOT_LOGGED_MSG);
		}
		return json;
	}
	
	/**
	 *文章评论
	 */
	@RequestMapping("articleComment")
	@ResponseBody
	public JsonObj articleComment(@RequestParam("commentContent") String commentContent,@RequestParam("articleId") Integer articleId,HttpServletRequest request,HttpSession session){
		JsonObj json = new JsonObj();
		User user = (User) session.getAttribute("user");
		if(user != null){
			ArticleComment c = new ArticleComment();
			c.setUser(user);
			c.setArticleId(articleId);
			ArticleComment comment = articleCommentService.selectIsExist(c);
			if(comment == null){
				comment = new ArticleComment();
				//过滤敏感词
				List<SensitiveWord> words = sensitiveWordService.selectAll();
				for (SensitiveWord word : words) {
					commentContent = commentContent.replaceAll(word.getWord(), "***");
				}
				comment.setCommentContent(commentContent);
				comment.setCommentDate(new Date());
				comment.setUserId(user.getId());
				comment.setArticleId(articleId);
				boolean success = articleCommentService.insertSelective(comment);
				String msg= "评论成功!";
				if(success){
					json.setSuccess(success);
				}else{
					msg = "评论失败!";
					success = false;
					json.setCode(102);
				}
				json.setObject(comment);
				json.setSuccess(success);
				json.setMessage(msg);
			}else{
				json.setSuccess(false);
				json.setMessage("你已评论过，请勿重复评论!");
				json.setCode(101);
			}
		}else{
			json.setSuccess(false);
			json.setMessage("对不起，请登陆之后再评论!");
			json.setCode(100);
		}
	
		return json;
	}
	
	/**
	 *发表文章页面
	 */
	@RequestMapping("publishArticle")
	public String publishArticle(HttpServletRequest request){
		List<ArticleType> articleTypes = articleTypeService.selectAll();
		request.setAttribute("articleTypes", articleTypes);
		return rootPath+"article/publishArticle";
	}
	
	@RequestMapping("publishArticleSave/{articleTypeId}")
	@ResponseBody
	public JsonObj publishArticleSave(@PathVariable("articleTypeId")Integer articleTypeId,Article article,HttpServletRequest request,HttpSession session){
			JsonObj json = new JsonObj();
			User user = (User) session.getAttribute("user");
			ArticleType articleType = articleTypeService.selectByPrimaryKey(articleTypeId);
			article.setUser(user);
			article.setArticleType(articleType);
			boolean success = articleService.insert(article);
			if(success){
				json.setMessage("添加成功!");
			}else{
				json.setMessage("添加失败!");
			}
			json.setSuccess(true);
			json.setObject(article);
			return json;
	}
	
	/**
	 * 关注文章作者
	 */
	@RequestMapping("attentionArticleAuth")
	@ResponseBody
	public JsonObj attentionArticleAuth(Integer userId,HttpServletRequest request,HttpSession session){
		JsonObj json = new JsonObj();
		User user = (User) session.getAttribute("user");
		if(user != null){
			if(user.getId().intValue() == userId.intValue()){//自己关注自己
				json.setMessage(Constant.FAIL_ATENTIONSELF_MSG);
				json.setCode(Constant.FAIL101);
				json.setSuccess(Constant.F);
			}else{
				UserFriend friend = new UserFriend();
				friend.setUserFriendId(userId);
				friend.setUserId(user.getId());
				UserFriend f = userFriendService.selectHasExists(friend);
				if(f == null){//没有收藏过
					boolean success =  userFriendService.insertSelective(friend);
					if(success){//成功
						json.setMessage(Constant.SUCCESS_MSG);
						json.setCode(Constant.SUCCESS100);
						json.setSuccess(Constant.S);
					}else{//失败
						json.setMessage(Constant.FAIL_MSG);
						json.setCode(Constant.FAIL101);
						json.setSuccess(Constant.F);
					}
				}else{//已经收藏过
					json.setMessage(Constant.FAIL103_2_MSG);
					json.setCode(Constant.FAIL103);
					json.setSuccess(Constant.F);
				}
			}
		}else{//未登录
			json.setMessage(Constant.NOT_LOGGED_MSG);
			json.setCode(Constant.NOT_LOGGED102);
			json.setSuccess(Constant.F);
		}
		return json;
	}
	
	/**
	 *给文章作者发私信
	 */
	@RequestMapping("sendPrivateMsg")
	@ResponseBody
	public JsonObj sendPrivateMsg(Integer userId,HttpServletRequest request,HttpSession session){
		JsonObj json = new JsonObj();
		User user = (User) session.getAttribute("user");
		if(user != null){
			json.setMessage(Constant.SUCCESS_MSG);
			json.setSuccess(Constant.S);
		}else{//未登录
			json.setMessage(Constant.NOT_LOGGED_MSG);
			json.setSuccess(Constant.F);
		}
		return json;
	}
	
	/**
	 * 单个文章类别的内容
	 * */
	@RequestMapping("byArticleTypeList/{id}")
	public  String byArticleTypeList(@PathVariable("id")Integer id,HttpServletRequest request){
		Map< String, Object> map = new HashMap<String, Object>();
		map.put("articleTypeId", id);
		Integer total =  articleService.selectByTypeTotal(id);
		String pageNow = request.getParameter("pageNow");
		if(pageNow != null){
			page = new Page(Integer.parseInt(pageNow),total,10);
		}else{
			page = new Page(1,total,10);
		}
		map.put("startPos", page.getStartPos());
		map.put("pageSize", page.getPageSize());
		List<Article> articles =	articleService.selectByType(map);
		request.setAttribute("total", total);
		request.setAttribute("page", page);
		request.setAttribute("articles", articles);
		request.setAttribute("articleTypeId", id);//类别ID
		return rootPath+"article/articleTypeList";
	}
	
	/**
	 * 文章所有类别
	 * */
	@RequestMapping("articleTypeList")
	@ResponseBody
	public  List<ArticleType> articleTypeList(HttpServletRequest request){
		List<ArticleType> list = articleTypeService.selectAll();
		return list;
	}
	
	/**
	 * 单个文章大类更多
	 * @param pageNow
	 * @param request
	 * @return
	 */
	@RequestMapping("articleTypeShowList/{flag}/{category}")
	public String articleTypeShowList(@PathVariable("flag")Integer flag,@PathVariable("category")Integer category,Integer pageNow,HttpServletRequest request){
			Map<String,Object> map = new HashMap<String, Object>();
			Integer total = articleService.selectByCategoryTypeTotal(category);
			page = new Page(pageNow,total,15);
			map.put("category", category);
			map.put("flag", flag);
			map.put("startPos", page.getStartPos());
			map.put("pageSize", page.getPageSize());
			List<Article> articles = articleService.selectByCategoryType(map);
			request.setAttribute("total", total);
			request.setAttribute("page", page);
			request.setAttribute("articles", articles);
			request.setAttribute("category", category);
			return rootPath+"article/articleTypeShowList";
	}
	
}
